<template>
  <VanSticky class="home-header" :class="cssClass" ref="root">
    <BaseSection v-bind="$attrs" space="0">
      <BaseCard
        class="home-header__main"
        gap="sm"
        bg="transparent"
        :is-radius="false"
      >
        <slot>
          <!-- <VanImage class="home-header__logo" :src="Img" /> -->
          <BaseText>欢迎来到一粒玩</BaseText>
        </slot>

        <VanSearch
          v-if="!noSearch"
          v-model="keyword"
          shape="round"
          :clearable="false"
          placeholder="请输入商品名称、分类"
          @search="onSearch"
          @click-left-icon="onSearch"
        />
        <slot name="right">
          <BaseText
            v-if="!noRight"
            is-icon
            size="xl"
            :name="mineIcon"
            @click="goMine"
          />
        </slot>
      </BaseCard>
    </BaseSection>
  </VanSticky>
</template>

<script setup>
import Img from "@/assets/home/logo.png";
import mineIcon from "@/assets/home/tabBar/mine.svg";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useScrollParent, useEventListener } from "@vant/use";

const props = defineProps({
  fixed: Boolean,
  noSearch: {
    type: Boolean,
    default: true,
  },
  noRight: {
    type: Boolean,
    default: true,
  },
});

const root = ref();
const hasBg = ref(false);
if (props.fixed) {
  const scrollParent = useScrollParent(root);
  useEventListener(
    "scroll",
    (e) => {
      hasBg.value = e.currentTarget.pageYOffset > 30;
    },
    { target: scrollParent }
  );
}

const cssClass = computed(() => {
  return {
    "home-header--fixed": props.fixed,
    "home-header--bg": hasBg.value,
  };
});

const router = useRouter();

const keyword = ref("");
const onSearch = () => {
  if (keyword.value && keyword.value.trim()) {
    let word = keyword.value;
    keyword.value = "";
    router.push({
      name: "search",
      query: {
        keyword: word,
      },
    });
  }
};

const goMine = () => {
  router.replace({
    name: "mine",
  });
};
</script>

<style lang="scss" scoped>
.home-header {
  z-index: 999;
  width: 100%;
  color: var(--dx-color-white);
  &--fixed {
    position: fixed;
    .base-section {
      background: transparent;
    }
  }
  &--bg {
    .base-section {
      background: var(--dx-color-nav-bar);
    }
  }
  &__main {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: var(--dx-gap-sm);
    min-height: 48px;
  }
  &__bar-item {
    font-size: 20px;
    margin-right: var(--dx-gap-md);
  }
  &__logo {
    height: 1.5em;
    width: auto;

    ::v-deep(.van-image__img) {
      width: auto;
    }
  }
}
.van-search {
  --van-field-icon-size: 1.3em;
  --van-search-padding: 0;
  flex: 1 1 0;
}
.base-section {
  background: var(--dx-color-nav-bar);
}
</style>
